<!DOCTYPE html>
<html>
<head>
    <title>我</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width = device-width , initial-scale = 1 , minimum-scale = 1 , maximum-scale = 1 , user-scalable = no">
    <link rel="stylesheet" href="../../resource/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../resource/css/common.css">
</head>
<body>
<div class="loading">
    <img src="../../resource/images/loading.jpg"/>
</div>
<div id="header">
    <a href="javascript:void(0)" class="nav-back">返回</a>
    我
    <span class="btn-user-set"></span>
</div>

<div class="main-content">
    <div class="detail-part">

        <div class="detail-head">

        </div>
    </div>
    <div id="coupon-box">
    </div>
</div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-body">
            </div>

        </div>
    </div>
</div>
<!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
<script src="../../resource/js/jquery.min.js"></script>
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="../../resource/js/bootstrap.min.js"></script>
<script src="../../resource/js/commonjs.js"></script>
<script src="http://api.map.baidu.com/api?v=2.0&ak=qVrWQw9Vs8t7iPfG7bSj0137" type="text/javascript"></script>
<script type="text/javascript">
    var longitude = null;
    var latitude = null;
    var count = null;
    var limit = null;
    var allLoad = null;//判断是否加载完毕
    var isFirstTime = null;//判断是否为第一次加载
    var loadControl = null;//控制每次只加载一下次

    $(function() {
        isLogin();
        $(".btn-user-set").click(function () {
            location.href = "userInfoSetting.html?url=1";
        });
        innit();
        loadMoreCouponBind();
    });
    /**/
    /* 初始化页面 */
    function innit() {
        getUserDetail();
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function(r){
            if(this.getStatus() == BMAP_STATUS_SUCCESS){
                longitude = r.point.lng;
                latitude = r.point.lat;
                count = 1;
                limit = 6;
                allLoad = false;
                isFirstTime = true;
                getCoupons();
            }
            else {
                alert('failed'+this.getStatus());
            }
        },{enableHighAccuracy: true})
    }
    /* 获取用户信息 */
    function getUserDetail() {
        var url = "/UserCenter/getUserDetail";
        var arg = {};
        ajaxJsonp(url, arg, renderUserDetail);
    }
    /* 渲染用户信息 */
    function renderUserDetail(res) {
        var userInfo = res.data.user_info;
        var couponNum = res.data.coupon_num;
        var giving_shop = res.data.giving_shop;
        var html = "";
        html += '<span class="btn-message"></span>';
        if(!userInfo.avatar) {
            html += '<img src="../../resource/images/head-image.jpg" class="user-headImage"/>';
        } else {
            html += '<img src="'+ userInfo.avatar +'" class="user-headImage"/>';
        }
        if(userInfo.nickname) {
            html += '<strong class="user-name">' + userInfo.nickname + '</strong>';
        } else {
            html += '<strong class="user-name">' + userInfo.mobile + '</strong>';
        }
        html += '<ul>';
        html += '<li class="user-stuff" id="user-prefer"><i class="user-stuff-icon bgl"></i>'+ giving_shop +'</li>';
        html += '<li class="user-stuff" id="user-point"><i class="user-stuff-icon"></i>' + userInfo.credit + '</li>';
        html += '<li class="user-stuff" id="user-coupon"><i class="user-stuff-icon bgr"></i>' + couponNum + '</li>';
        html += '</ul>';
        $(".detail-head").append(html);
        var h = $(".detail-part").height();
        $(".loading").animate({"top": h + 50});
    }
    /* 获取优惠券 */
    function getCoupons() {
        var url = "/UserCenter/getCoupon";
        var arg = {};
        arg.longitude =longitude;
        arg.latitude = latitude;
        arg.num = 6;
        arg.page = count;
        count ++;
        ajaxJsonp(url, arg, renderCoupon);
    }
    /* 渲染优惠券 */
    function renderCoupon(res) {
        if(limit > res.data.length) {
            allLoad = true;
        }
        var datas = res.data;
        var html = "";
            if(!isFirstTime) {
                $("#coupon-box").append("<div class='load-more'><img src='../../resource/images/loading.jpg'/></div>");
            }
            for(var i = 0; i < datas.length; i++) {
                var distance = datas[i].distance.toFixed(1);
                var stt = timeChange(datas[i].start_time)
                var ext = timeChange(datas[i].expired_time);
                if(datas[i].distance < 1) {
                    distance *= 1000;
                    distance += 'm';
                } else {
                    distance += 'km';
                }
                html += '<div class="coupon-content" id="'+ datas[i].coupon_code +'">';
                html += '<div class="coupon-left">';
                html += '<img class="seller-img" src="'+ datas[i].image +'"/>';
                html += '</div>';
                html += '<div class="coupon-detail">';
                html += '<strong class="seller-name">' + datas[i].shop_name + '</strong>';
                html += '<strong class="seller-sale">' + datas[i].discount + '折</strong>';
                html += '<span class="seller-tag seller-detail">' + datas[i].tag + '</span>';
                html += '<span class="seller-dis seller-detail">' + distance + '</span>';
                html += '<span class="coupon-time seller-detail">' + stt + '-' + ext + '</span>';
                html += '</div>';
                html += '<div class="coupon-method">';
                if(datas[i].status == "1"){
                    html += '<strong class="coupon-status coupon-release">发布</strong>';
                    html += '<strong class="coupon-operate use">使用</strong>';
                } else if(datas[i].status == "3") {
                    html += '<strong class="coupon-status coupon-released">已发布</strong>';
                    html += '<strong class="coupon-operate cancel">取消</strong>';
                } else if(datas[i].status == "2") {
                    html += '<strong class="coupon-status coupon-used">已使用</strong>';
                    html += '<strong class="coupon-operate remove">删除</strong>';
                } else if(datas[i].status == "4") {
                    html += '<strong class="coupon-status coupon-gave">已领取</strong>';
                    html += '<strong class="coupon-operate remove">删除</strong>';
                }
            html += '</div>';
            html += '</div>';
        }
        if(isFirstTime) {
            if(!datas.length) {
                html += "<h1 class='tips'>你还没有领取优惠券</h1>";
            }
            $("#coupon-box").append(html);
            $(".loading").hide();
            releaseCouponBind();
            deleteCouponBind();
            useCouponBind();
            cancelReleaseBind();
            loadControl = true;
        } else {
            setTimeout(function () {
                $(".load-more").remove();
                $("#coupon-box").append(html);
                loadControl = true;
            }, 500);
        }

    userInfoEvenBind();
    }
    /* 用户主页事件绑定 */
    function userInfoEvenBind() {
        $('.btn-message').click(function() {
            event.stopPropagation();
            $(this).addClass("clicked");
            location.href = "userMessage.html?url=1";
        });
        $(".nav-back").click(function () {
            location.href = "../../index.html?url=1";
        })
        $(".user-headImage").on("click",function(){
            location.href = "userImage.html?url=1";
        });
    }
    /* 绑定删除优惠券事件 */
    function deleteCouponBind() {
        $("#coupon-box").delegate(".remove","click",function(){
            event.stopPropagation();
            var $target = $(this).parent().parent();
            var id = $target.attr("id");
            deleteCoupon(id);
            var w = $target.width();
            $target.css("position","relative");
            $target.animate({"left": -w,"height":0},300);
            setTimeout(function () {
                $target.fadeOut().remove();
            },200);
        });
    }
    /* 绑定使用优惠券 */
    function useCouponBind() {
        $("#coupon-box").delegate(".use","click",function(){
            event.stopPropagation();
            var $target = $(this).parent().parent();
            var id = $target.attr("id");
            location.href = "userUseCoupon.html?code_id=" + id;
            //useCoupon(id);
        });
    }
    /* 使用优惠券 */
    function useCoupon(id) {
        var url = "/UserCenter/useCoupon";
        var arg = {};
        arg.coupon_code = id;
        ajaxJsonp(url, arg);
    }
    /* 删除优惠券 */
    function deleteCoupon(id) {
        var url = "/UserCenter/deleteCoupon";
        var arg = {};
        arg.coupon_code = id;
        ajaxJsonp(url, arg);
    }
    /* 绑定发布优惠券事件 */
    function releaseCouponBind() {
        $("#coupon-box").delegate(".coupon-release","click",function(){
            event.stopPropagation();
            $(this).addClass("clicked");
            var code = $(this).parent().parent().attr("id");
            location.href = "userCouponRelease.html?code=" + code + "&longitude=" + longitude + "&latitude=" + latitude;
        });

    }
    /* 取消发布绑定事件 */
    function cancelReleaseBind() {
        $("#coupon-box").delegate(".cancel","click",function(){
            event.stopPropagation();
            $(this).text("使用");
            $(this).removeClass("cancel").addClass("use");
            $(this).parent().find(".coupon-status").text("发布").removeClass("coupon-released").addClass("coupon-release");
            var id = $(this).parent().parent().attr("id");
            cancelPublishCoupon(id);
        });
    }
    /* 取消发布 */
    function cancelPublishCoupon(id) {
        var url = "/UserCenter/cancelPublishCoupon";
        var arg = {};
        arg.coupon_code = id;
        ajaxJsonp(url, arg, cancelSuc);
    }
    /* 取消成功 */
    function cancelSuc(res) {
        showModal("取消成功");
    }
    /* 优惠券滚动加载 */
    function loadMoreCouponBind(){
        $(window).scroll(function() {
            var scrollHeight = $(window).scrollTop();
            var totalHeight = document.body.clientHeight;
            var viewHeight = $(window).height();
            if((scrollHeight + viewHeight) == totalHeight && !allLoad) {
                if(loadControl) {
                    loadControl = false;
                    isFirstTime = false;
                    getCoupons();
                }
            }
        })
    }
</script>
</body>
</html>